package com.ruoyi.manage.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Calendar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.manage.mapper.CrRecruitmentMapper;
import com.ruoyi.manage.mapper.CrApplicationMapper;
import com.ruoyi.manage.domain.CrRecruitment;
import com.ruoyi.manage.domain.CrApplication;
import com.ruoyi.manage.service.ICrRecruitmentService;

/**
 * 社团招聘Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-24
 */
@Service
public class CrRecruitmentServiceImpl implements ICrRecruitmentService 
{
    @Autowired
    private CrRecruitmentMapper crRecruitmentMapper;

    @Autowired
    private CrApplicationMapper crApplicationMapper;

    /**
     * 查询社团招聘
     * 
     * @param recruitmentId 社团招聘主键
     * @return 社团招聘
     */
    @Override
    public CrRecruitment selectCrRecruitmentByRecruitmentId(Long recruitmentId)
    {
        return crRecruitmentMapper.selectCrRecruitmentByRecruitmentId(recruitmentId);
    }

    /**
     * 查询社团招聘列表
     * 
     * @param crRecruitment 社团招聘
     * @return 社团招聘
     */
    @Override
    public List<CrRecruitment> selectCrRecruitmentList(CrRecruitment crRecruitment)
    {
        return crRecruitmentMapper.selectCrRecruitmentList(crRecruitment);
    }

    /**
     * 新增社团招聘
     * 
     * @param crRecruitment 社团招聘
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCrRecruitment(CrRecruitment crRecruitment)
    {
        crRecruitment.setCreateTime(DateUtils.getNowDate());
        return crRecruitmentMapper.insertCrRecruitment(crRecruitment);
    }

    /**
     * 修改社团招聘
     * 
     * @param crRecruitment 社团招聘
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCrRecruitment(CrRecruitment crRecruitment)
    {
        crRecruitment.setUpdateTime(DateUtils.getNowDate());
        return crRecruitmentMapper.updateCrRecruitment(crRecruitment);
    }

    /**
     * 批量删除社团招聘
     * 
     * @param recruitmentIds 需要删除的社团招聘主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCrRecruitmentByRecruitmentIds(Long[] recruitmentIds)
    {
        return crRecruitmentMapper.deleteCrRecruitmentByRecruitmentIds(recruitmentIds);
    }

    /**
     * 删除社团招聘信息
     * 
     * @param recruitmentId 社团招聘主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteCrRecruitmentByRecruitmentId(Long recruitmentId)
    {
        return crRecruitmentMapper.deleteCrRecruitmentByRecruitmentId(recruitmentId);
    }

    /**
     * 根据社团ID查询招聘列表
     * 
     * @param clubId 社团ID
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> selectRecruitmentsByClubId(Long clubId)
    {
        return crRecruitmentMapper.selectRecruitmentListByClubId(clubId);
    }

    /**
     * 根据状态查询招聘列表
     * 
     * @param status 招聘状态
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> selectRecruitmentsByStatus(String status)
    {
        CrRecruitment queryParam = new CrRecruitment();
        queryParam.setStatus(status);
        return crRecruitmentMapper.selectCrRecruitmentList(queryParam);
    }

    /**
     * 搜索招聘信息
     * 
     * @param keyword 关键词
     * @param clubType 社团类型
     * @param status 招聘状态
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> searchRecruitments(String keyword, String clubType, String status)
    {
        List<CrRecruitment> recruitments = crRecruitmentMapper.searchRecruitmentList(keyword, clubType);
        
        // 如果指定了状态，进行额外过滤
        if (StringUtils.isNotEmpty(status)) {
            recruitments.removeIf(recruitment -> !status.equals(recruitment.getStatus()));
        }
        
        return recruitments;
    }

    /**
     * 发布招聘信息
     * 
     * @param crRecruitment 招聘信息
     * @return 结果
     */
    @Override
    @Transactional
    public int publishRecruitment(CrRecruitment crRecruitment)
    {
        // 验证必填字段
        if (StringUtils.isEmpty(crRecruitment.getTitle())) {
            throw new RuntimeException("招聘标题不能为空");
        }
        if (StringUtils.isEmpty(crRecruitment.getPositionName())) {
            throw new RuntimeException("职位名称不能为空");
        }
        if (crRecruitment.getEndDate() == null) {
            throw new RuntimeException("截止时间不能为空");
        }
        if (crRecruitment.getEndDate().before(new Date())) {
            throw new RuntimeException("截止时间不能早于当前时间");
        }

        // 设置初始状态和统计数据
        crRecruitment.setStatus("0"); // 招聘中
        crRecruitment.setViewCount(0);
        crRecruitment.setAppliedCount(0);
        crRecruitment.setCreateTime(DateUtils.getNowDate());

        return crRecruitmentMapper.insertCrRecruitment(crRecruitment);
    }

    /**
     * 关闭招聘
     * 
     * @param recruitmentId 招聘ID
     * @param clubId 社团ID
     * @return 结果
     */
    @Override
    @Transactional
    public int closeRecruitment(Long recruitmentId, Long clubId)
    {
        CrRecruitment recruitment = crRecruitmentMapper.selectCrRecruitmentByRecruitmentId(recruitmentId);
        if (recruitment == null) {
            throw new RuntimeException("招聘信息不存在");
        }

        if (!recruitment.getClubId().equals(clubId)) {
            throw new RuntimeException("只能关闭本社团的招聘");
        }

        if (!"0".equals(recruitment.getStatus())) {
            throw new RuntimeException("只能关闭进行中的招聘");
        }

        recruitment.setStatus("2"); // 已结束
        recruitment.setUpdateTime(DateUtils.getNowDate());

        return crRecruitmentMapper.updateCrRecruitment(recruitment);
    }

    /**
     * 重新开放招聘
     * 
     * @param recruitmentId 招聘ID
     * @param clubId 社团ID
     * @return 结果
     */
    @Override
    @Transactional
    public int reopenRecruitment(Long recruitmentId, Long clubId)
    {
        CrRecruitment recruitment = crRecruitmentMapper.selectCrRecruitmentByRecruitmentId(recruitmentId);
        if (recruitment == null) {
            throw new RuntimeException("招聘信息不存在");
        }

        if (!recruitment.getClubId().equals(clubId)) {
            throw new RuntimeException("只能重新开放本社团的招聘");
        }

        if (!"2".equals(recruitment.getStatus())) {
            throw new RuntimeException("只能重新开放已结束的招聘");
        }

        // 检查截止时间是否已过
        if (recruitment.getEndDate().before(new Date())) {
            throw new RuntimeException("招聘截止时间已过，无法重新开放");
        }

        recruitment.setStatus("0"); // 招聘中
        recruitment.setUpdateTime(DateUtils.getNowDate());

        return crRecruitmentMapper.updateCrRecruitment(recruitment);
    }

    /**
     * 增加浏览量
     * 
     * @param recruitmentId 招聘ID
     * @return 结果
     */
    @Override
    public int increaseViewCount(Long recruitmentId)
    {
        return crRecruitmentMapper.updateViewCount(recruitmentId);
    }

    /**
     * 获取热门招聘（根据浏览量和申请数量）
     * 
     * @param limit 数量限制
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> getPopularRecruitments(int limit)
    {
        return crRecruitmentMapper.selectFeaturedRecruitmentList(limit);
    }

    /**
     * 获取最新招聘
     * 
     * @param limit 数量限制
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> getLatestRecruitments(int limit)
    {
        CrRecruitment queryParam = new CrRecruitment();
        queryParam.setStatus("0"); // 只查询招聘中的
        List<CrRecruitment> allRecruitments = crRecruitmentMapper.selectActiveRecruitmentList(queryParam);
        
        // 按创建时间排序并限制数量
        return allRecruitments.stream()
                .sorted((r1, r2) -> r2.getCreateTime().compareTo(r1.getCreateTime()))
                .limit(limit)
                .collect(java.util.stream.Collectors.toList());
    }

    /**
     * 获取即将截止的招聘
     * 
     * @param days 天数（几天内截止）
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> getExpiringRecruitments(int days)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, days);
        Date expiryDate = calendar.getTime();

        CrRecruitment queryParam = new CrRecruitment();
        queryParam.setStatus("0"); // 0表示招聘中
        List<CrRecruitment> allRecruitments = crRecruitmentMapper.selectActiveRecruitmentList(queryParam);

        // 过滤出即将截止的招聘
        return allRecruitments.stream()
                .filter(recruitment -> recruitment.getEndDate().before(expiryDate) && recruitment.getEndDate().after(new Date()))
                .collect(java.util.stream.Collectors.toList());
    }

    /**
     * 获取社团招聘统计
     * 
     * @param clubId 社团ID
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getClubRecruitmentStatistics(Long clubId)
    {
        Map<String, Object> statistics = new HashMap<>();
        
        List<CrRecruitment> allRecruitments = crRecruitmentMapper.selectRecruitmentListByClubId(clubId);
        statistics.put("totalRecruitments", allRecruitments.size());

        // 按状态统计
        long activeCount = allRecruitments.stream().filter(r -> "1".equals(r.getStatus())).count();
        long completedCount = allRecruitments.stream().filter(r -> "2".equals(r.getStatus())).count();
        long draftCount = allRecruitments.stream().filter(r -> "0".equals(r.getStatus())).count();

        statistics.put("activeCount", activeCount);
        statistics.put("completedCount", completedCount);
        statistics.put("draftCount", draftCount);

        // 总浏览量和申请量
        int totalViews = allRecruitments.stream().mapToInt(r -> r.getViewCount() != null ? r.getViewCount() : 0).sum();
        int totalApplications = allRecruitments.stream().mapToInt(r -> r.getAppliedCount() != null ? r.getAppliedCount() : 0).sum();

        statistics.put("totalViews", totalViews);
        statistics.put("totalApplications", totalApplications);

        return statistics;
    }

    /**
     * 获取招聘统计信息
     * 
     * @param recruitmentId 招聘ID
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getRecruitmentStatistics(Long recruitmentId)
    {
        Map<String, Object> statistics = new HashMap<>();
        
        CrRecruitment recruitment = crRecruitmentMapper.selectCrRecruitmentByRecruitmentId(recruitmentId);
        if (recruitment == null) {
            return statistics;
        }

        statistics.put("viewCount", recruitment.getViewCount());
        statistics.put("appliedCount", recruitment.getAppliedCount());

        // 获取申请详细统计
        List<CrApplication> applications = crApplicationMapper.selectApplicationListByRecruitmentId(recruitmentId);
        
        long pendingCount = applications.stream().filter(app -> "0".equals(app.getStatus())).count();
        long approvedCount = applications.stream().filter(app -> "2".equals(app.getStatus())).count();
        long rejectedCount = applications.stream().filter(app -> "3".equals(app.getStatus())).count();

        statistics.put("pendingApplications", pendingCount);
        statistics.put("approvedApplications", approvedCount);
        statistics.put("rejectedApplications", rejectedCount);

        return statistics;
    }

    /**
     * 检查招聘是否可申请
     * 
     * @param recruitmentId 招聘ID
     * @return 是否可申请
     */
    @Override
    public boolean isRecruitmentAvailable(Long recruitmentId)
    {
        CrRecruitment recruitment = crRecruitmentMapper.selectCrRecruitmentByRecruitmentId(recruitmentId);
        if (recruitment == null) {
            return false;
        }

        // 检查状态和截止时间
        return "0".equals(recruitment.getStatus()) && recruitment.getEndDate().after(new Date());
    }

    /**
     * 获取推荐招聘（基于学生兴趣和技能）
     * 
     * @param studentId 学生ID
     * @param limit 数量限制
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> getRecommendedRecruitments(Long studentId, int limit)
    {
        return crRecruitmentMapper.selectMatchedRecruitmentList(studentId, limit);
    }

    /**
     * 更新招聘申请统计
     * 
     * @param recruitmentId 招聘ID
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRecruitmentApplicationStats(Long recruitmentId)
    {
        List<CrApplication> applications = crApplicationMapper.selectApplicationListByRecruitmentId(recruitmentId);
        int applicationCount = applications.size();
        
        return crRecruitmentMapper.updateAppliedCount(recruitmentId, applicationCount);
    }

    /**
     * 批量更新招聘状态
     * 
     * @param recruitmentIds 招聘ID数组
     * @param status 新状态
     * @return 结果
     */
    @Override
    @Transactional
    public int batchUpdateRecruitmentStatus(Long[] recruitmentIds, String status)
    {
        if (recruitmentIds == null || recruitmentIds.length == 0) {
            throw new RuntimeException("请选择要更新的招聘");
        }

        // 验证状态值
        if (!("0".equals(status) || "1".equals(status) || "2".equals(status))) {
            throw new RuntimeException("无效的招聘状态");
        }

        return crRecruitmentMapper.batchUpdateRecruitmentStatus(recruitmentIds, status);
    }

    /**
     * 导出招聘数据
     * 
     * @param crRecruitment 查询条件
     * @return 招聘列表
     */
    @Override
    public List<CrRecruitment> exportRecruitments(CrRecruitment crRecruitment)
    {
        return crRecruitmentMapper.selectCrRecruitmentList(crRecruitment);
    }
}